package com.sunnada.weixin.util.weixinPay;



import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunnada.weixin.util.weixinPay.Constant;

public class WeiXinUtil {

	private static final Logger log = LoggerFactory.getLogger(WeiXinUtil.class);

	public static String connectWeiXinInterface(String action, String json) {
		byte[] bts = connectWeiXinInterfaceForByte(action, json);
		String result = "";
		if(null != bts) {
			result = new String(bts, Charset.forName("UTF-8"));
		}
		log.info("请求:{},响应:{}", action, result);
		return result;
	}
	
	public static byte[] connectWeiXinInterfaceForByte(String action, String json) {
		log.info("请求:{}, 参数:{}", action, json);
		try {
			URL url = new URL(action);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "60000");// 连接超时60秒
			System.setProperty("sun.net.client.defaultReadTimeout", "60000"); // 读取超时60秒
			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(json.getBytes("UTF-8"));// 传入参数
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			os.flush();
			os.close();
			return jsonBytes;
		} catch (Exception e) {
			log.info("请求微信接口失败，失败信息:{}", e);
			return null;
		}
	}
	
	public static String postDirectByURIConnection(String uri, Map<String, String> formParams, Map<String, File> fileParams, String encode) throws Exception {
		log.info("请求:{}", uri);
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		URL url = new URL(uri);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(Constant.WEIXIN.CONNECT_TIMEOUT);
		conn.setReadTimeout(Constant.WEIXIN.READ_TIMEOUT);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", encode);
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
		StringBuilder sb = new StringBuilder();

		if (formParams != null)
			for (Map.Entry<String, String> entry : formParams.entrySet()) {
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINEND);
				sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
				sb.append("Content-Type: text/plain; charset=" + encode + LINEND);
				sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
				sb.append(LINEND);
				sb.append(entry.getValue());
				sb.append(LINEND);
			}

		DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
		outStream.write(sb.toString().getBytes());
		if (fileParams != null)
			for (Map.Entry<String, File> file : fileParams.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset=" + encode + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());
				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}
				is.close();
				outStream.write(LINEND.getBytes());
			}
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		outStream.close();
//		int res = conn.getResponseCode();

		StringBuilder data = new StringBuilder();
//		if (res == HttpURLConnection.HTTP_OK) {
			BufferedReader bufReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = bufReader.readLine()) != null) {
				data.append(line);
			}
			
			bufReader.close();
			conn.disconnect();
//		} else {
//			conn.disconnect();
//		}

		return data.toString();
	}
}
